<template>
  <el-dialog title="选择用户" v-model="visible" width="80%" @close="handleClose">
    <div class="handle-box">
      <el-input v-model="search.authorNo" placeholder="作者号" class="handle-input mb10" clearable></el-input>
      <el-input v-model="search.loginName" placeholder="用户登录名" class="handle-input mb10" clearable></el-input>
      <el-input v-model="search.nickname" placeholder="用户昵称" class="handle-input" clearable></el-input>
      <el-input v-model="search.mobile" placeholder="手机号" class="handle-input" clearable></el-input>
      <el-date-picker v-model="search.createTimeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" class="handle-input mr10" format="YYYY-MM-DD" clearable></el-date-picker>
      <!-- <el-select v-model="search.status" placeholder="用户状态" class="handle-input" clearable>
        <el-option label="未冻结" value="1"></el-option>
        <el-option label="冻结" value="0"></el-option>
      </el-select> -->
      <el-button type="primary" icon="el-icon-search" @click="getData()">搜索</el-button>
    </div>

    <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
      @selection-change="handleSelectionChange" @select-all="handleSelectionChange" @row-click="handleRowClick"
      :row-class-name="getRowClassName">
      <el-table-column v-if="multiple" type="selection" width="55"></el-table-column>
      <el-table-column v-else width="55" label="选择">
        <template #default="scope">
          <el-radio v-model="selectedUserId" :label="scope.row.userId" @change="handleRadioChange(scope.row)">
            <span></span>
          </el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID"></el-table-column>
      <el-table-column prop="loginName" label="用户名"></el-table-column>
      <el-table-column prop="mobile" label="手机号"></el-table-column>
      <el-table-column prop="nickname" label="用户昵称"></el-table-column>
      <el-table-column prop="wechatOpenId" label="微信openID">
        <template #default="scope">
          <span>{{ scope.row.wechatOpenId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="qqOpenId" label="QQOPENID">
        <template #default="scope">
          <span>{{ scope.row.qqOpenId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userPic" label="用户头像">
        <template #default="scope">
          <img v-if="scope.row.userPic" :src="scope.row.userPic"
            style="width: 40px; height: 40px; border-radius: 50%;" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" :formatter="dateFormat"></el-table-column>
      <el-table-column prop="shareFer" label="推荐人">
        <template #default="scope">
          <span>{{ scope.row.shareFer || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="inviteCode" label="邀请码" align="center"></el-table-column>
      <el-table-column label="用户状态">
        <template #default="scope">
          <el-tag>{{ scope.row.status == '0' ? '冻结' : '未冻结' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNo" :page-size="10"
        :total="query.pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm" :disabled="selectedUsers.length === 0">
          {{ multiple ? `确定选择 (${selectedUsers.length})` : '确定选择' }}
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>

<script>
import { api } from "@/api/index";
import moment from "moment";
export default {
  name: "selectUser",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: true
    },
    selectedUserIds: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      query: { pageNo: 1, pageTotal: 0 },
      tableData: [],
      search: {
        authorNo: '',
        loginName: '',
        nickname: '',
        mobile: '',
        createTimeRange: [],
        status: ''
      },
      selectedUsers: [],
      selectedUserId: null // 单选模式下选中的用户ID
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        // 弹窗打开时，先设置预选状态
        if (!this.multiple && this.selectedUserIds && this.selectedUserIds.length > 0) {
          this.selectedUserId = this.selectedUserIds[0];
        }
        this.getData();
      }
    },
    selectedUserIds: {
      handler() {
        if (this.visible && this.tableData.length > 0) {
          this.$nextTick(() => {
            this.setSelectedRows();
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 时间过滤器
    dateFormat: function (row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
    handleSelectionChange(selection) {
      this.selectedUsers = selection;
    },
    handleRowClick(row) {
      if (!this.multiple) {
        // 单选模式下，点击行直接选中
        this.selectedUserId = row.userId;
        this.selectedUsers = [row];
      }
    },
    handleRadioChange(row) {
      this.selectedUsers = [row];
    },
    getRowClassName({ row }) {
      if (!this.multiple && this.selectedUserId === row.userId) {
        return 'selected-row';
      }
      return '';
    },
    // 获取列表数据
    getData() {
      // 处理日期区间
      let startTime = '';
      let endTime = '';
      if (this.search.createTimeRange && this.search.createTimeRange.length === 2) {
        // 格式化日期为 YYYY-MM-DD 格式
        startTime = this.formatDate(this.search.createTimeRange[0]);
        endTime = this.formatDate(this.search.createTimeRange[1]);
      }

      api('/admin/subscribers/subList', {
        limit: 10,
        offset: this.query.pageNo,
        pid: this.$store.state.adminMsg.parentId,
        authorNo: this.search.authorNo,
        loginName: this.search.loginName,
        nickname: this.search.nickname,
        mobile: this.search.mobile,
        startTime: startTime,
        endTime: endTime,
        status: this.search.status,
      }).then((res) => {
        this.tableData = res.data.rows;
        this.query.pageTotal = res.data.total;

        // 设置已选中的行
        this.$nextTick(() => {
          this.setSelectedRows();
        });
      });
    },

    // 设置已选中的行
    setSelectedRows() {
      if (!this.selectedUserIds || this.selectedUserIds.length === 0) {
        return;
      }

      if (this.multiple) {
        // 多选模式
        this.$refs.multipleTable?.clearSelection();
        this.selectedUsers = [];

        this.tableData.forEach(row => {
          if (this.selectedUserIds.includes(row.userId)) {
            this.$refs.multipleTable?.toggleRowSelection(row, true);
            this.selectedUsers.push(row);
          }
        });
      } else {
        // 单选模式
        this.selectedUsers = [];
        this.selectedUserId = null;

        this.tableData.forEach(row => {
          if (this.selectedUserIds.includes(row.userId)) {
            this.selectedUserId = row.userId;
            this.selectedUsers.push(row);
          }
        });
      }
    },


    // 分页导航
    handlePageChange(val) {
      this.query.pageNo = val;
      this.getData();
    },

    // 关闭弹窗
    handleClose() {
      this.visible = false;
      this.selectedUsers = [];
      this.selectedUserId = null;
      this.search = {
        authorNo: '',
        loginName: '',
        nickname: '',
        mobile: '',
        createTimeRange: [],
        status: ''
      };
      this.query.pageNo = 1;
    },

    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedUsers);
      this.handleClose();
    },



  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 250px;
  display: inline-block;
  margin-right: 10px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.mb10 {
  margin-bottom: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

::v-deep .selected-row {
  background-color: #f0f9ff !important;
}

::v-deep .selected-row:hover {
  background-color: #e0f2fe !important;
}
</style>
